package com.example.stock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.stock.model.GoodsOrderProduct;
import com.example.stock.model.GoodsOrderShip;
import com.example.stock.utils.AsyncHttpUtils;
import com.example.stock.utils.JsonMapper;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

public class MainActivity extends ListActivity {

	private EditText input_barCode = null;
	private EditText input_storeName = null;
	private EditText input_shopName = null;
	private EditText input_contracts = null;
	private EditText input_phoneNumber = null;
	private EditText input_boxNo = null;
	private EditText input_expressNo = null;
	private EditText input_imes = null;
	private EditText input_remarks = null;

	private Button btn_clear_barCode=null;
	private Button btn_clear = null;
	private Button btn_save = null;
	private String baseUrl = "http://168.192.1.144:8080/blue/crm/goodsOrder/androidShip";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		getWindow().setTitle("666666666");
		
		input_barCode = (EditText) findViewById(R.id.input_barCode);
		input_storeName = (EditText) findViewById(R.id.input_storeName);
		input_shopName = (EditText) findViewById(R.id.input_shopName);
		input_shopName.setKeyListener(null); //设置门店多行输入框不可编辑
		input_contracts = (EditText) findViewById(R.id.input_contracts);
		input_phoneNumber = (EditText) findViewById(R.id.input_phoneNumber);
		input_boxNo = (EditText) findViewById(R.id.input_boxNo);
		input_imes = (EditText) findViewById(R.id.input_imes);
		input_expressNo = (EditText) findViewById(R.id.input_expressNo);
		input_remarks = (EditText) findViewById(R.id.input_remarks);

		btn_clear_barCode = (Button)findViewById(R.id.btn_clear_barCode);
		btn_clear = (Button) findViewById(R.id.btn_imeClear);
		btn_save = (Button) findViewById(R.id.btn_save);
		
		input_barCode.setFocusable(true);
		input_barCode.setFocusableInTouchMode(true);
		input_barCode.requestFocus();
		
		btn_clear_barCode.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				input_barCode.setText("");
				input_storeName.setText("");
				input_shopName.setText("");
				input_contracts.setText("");
				input_phoneNumber.setText("");
				cancelShowListView();
			}
		});
		
		input_barCode.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int count, int after) {
			}
			public void beforeTextChanged(CharSequence s, int start, int before, int count) {
			}

			// edit 输入结束呈现在输入框中的信息
		   //在afterTextChanged中，调用setText()方法会循环递归触发监听器，必须合理退出递归，不然会产生异常
			public void afterTextChanged(Editable editable) {
				String barCode = "";
				String regex = "[X|x][K|k][0-9]{8}";
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(editable.toString());
				//如果是通过扫码器
				if(editable.toString().length() == 12 && editable.toString().contains("\r\n")){
					barCode = input_barCode.getText().toString().replace("\r\n", "");
					input_barCode.setText(barCode);
				}
				if(editable.toString().length() == 10 && m.matches()){
					barCode = input_barCode.getText().toString();
					RequestParams  params = new RequestParams();
					params.put("orderNo", barCode);
					httpGet(baseUrl,params);
				}
				input_barCode.setSelection(input_barCode.getText().length());
			}
		});
		
		
		input_boxNo.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean isHasFocus) {
				if(isHasFocus){
					//得到焦点时
				}else{
					//失去焦点时，触发验证
					validate();
				}
			}
		});
		
		input_boxNo.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				validate();
				return false;
			}
		});
		
		input_boxNo.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) {
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
			@Override
			public void afterTextChanged(Editable text) {
				input_boxNo.setSelection(input_boxNo.getText().length());
			}
		});
		
		input_imes.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean isHasFocus) {
				if(isHasFocus){
					//得到焦点时
				}else{
					//失去焦点时，触发验证
					validate();
				}
			}
		});
		
		input_imes.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				validate();
				return false; 
			}
		});
		
		input_imes.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) {
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
			@Override
			public void afterTextChanged(Editable text) {
				input_imes.setSelection(input_imes.getText().length());
			}
		});

		// 串码清空操作
		btn_clear.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				input_imes.setText("");
			}
		});
		
		/**
		 * 点击保存事件
		 */
		btn_save.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				RequestParams  params = new RequestParams();
				params.put("orderNo", input_barCode.getText().toString());
				params.put("boxImeStr", input_boxNo.getText().toString());
				params.put("imeStr", input_imes.getText().toString());
				params.put("trackingNo", input_expressNo.getText().toString());
				params.put("shipFinished", 1);
				params.put("applyKey", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId()); //获取Android设备唯一ID
				httpGet(baseUrl, params);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override  
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId){
		case R.id.runAsOPPO:
			baseUrl = "http://ncoppo.com:86/oppo/crm/goodsOrder/androidShip";
			getWindow().setTitle("仓库发货_OPPO");
			break;
		case R.id.runAsVIVO:
			baseUrl = "http://ncoppo.com:86/bbk/crm/goodsOrder/androidShip";
			getWindow().setTitle("仓库发货_vivo");
			break;
		default:
			return false;
		}
	  return true;
	}

	//listView点击的事件监听回调
	@Override
	protected void onListItemClick(ListView listView, View view, int position, long id) {
		super.onListItemClick(listView, view, position, id);
		view.setBackgroundColor(Color.GREEN);
	}

	public void httpGet(String url,RequestParams params) {
		AsyncHttpUtils.get(url, params, new TextHttpResponseHandler() {
			@Override
			public void onFinish() {
			}

			/**
			 * 扫描条形码（订货单号）时触发事件 开始请求之后，首先走这个start方法，接下来进入onFinish，准备完毕，
			 * 能请求到数据的时候进入onSuccess， 当不能请求到数据的时候进入onFailure，这里可能包含了网络错误，链接错误等原因。
			 */
			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				new AlertDialog.Builder(getApplication()).setTitle("警告").setMessage("网络发生了异常").setPositiveButton("确定", null).show();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, String jsonResult) {
				GoodsOrderShip goodsOrderShip = JsonMapper.alwaysMapper().fromJson(jsonResult, GoodsOrderShip.class);
				String msg = goodsOrderShip.getStatusDesc();
				//发货成功
				if(goodsOrderShip.getStatus().equals("10000")){
					new AlertDialog.Builder(MainActivity.this).setTitle("订单"+goodsOrderShip.getOrderNo()+"发货成功").setMessage(msg).setPositiveButton("确定", null).show();
					input_barCode.setText("");
					input_storeName.setText("");
					input_shopName.setText("");
					input_contracts.setText("");
					input_phoneNumber.setText("");
					input_boxNo.setText("");
					input_imes.setText("");
					input_expressNo.setText("");
					input_remarks.setText("");
					cancelShowListView();
					input_barCode.setFocusable(true);
					input_barCode.setFocusableInTouchMode(true);
					input_barCode.requestFocus();
				}
				//正常扫码
				else if(goodsOrderShip.getStatus().equals("10001")){
					input_storeName.setText(goodsOrderShip.getStoreName().toString());
					input_shopName.setText(goodsOrderShip.getDepotName().toString());
					input_contracts.setText(goodsOrderShip.getContactor().toString());
					input_phoneNumber.setText(goodsOrderShip.getMobilePhone().toString());
					input_boxNo.setText(goodsOrderShip.getBoxIme());
					input_imes.setText(goodsOrderShip.getImeStr());
					showListView(goodsOrderShip.getGoodsOrderProducts());
				}else if(goodsOrderShip.getStatus().equals("10002")){
					new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage(msg).setPositiveButton("确定", null).show();
					input_barCode.setText("");
				}else if(goodsOrderShip.getStatus().equals("10003")){
					new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage(msg).setPositiveButton("确定", null).show();
					input_barCode.setText("");
				}else if(goodsOrderShip.getStatus().equals("10004")){
					new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage(msg).setPositiveButton("确定", null).show();
					input_barCode.setText("");
				}else if(goodsOrderShip.getStatus().equals("10005")){
					new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage(msg).setPositiveButton("确定", null).show();
					input_boxNo.setText(goodsOrderShip.getBoxIme().toString());
				}else if(goodsOrderShip.getStatus().equals("10006")){
					new AlertDialog.Builder(MainActivity.this).setTitle("系统提示").setMessage(msg).setPositiveButton("确定", null).show();
					input_imes.setText(goodsOrderShip.getImeStr().toString());
				}else{
					;
				}
			}
		});
	}
	
	/**
	 * 设置listView高度随着列表项数自动变化
	 * 
	 * @param listView
	 */
	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
		listView.setLayoutParams(params);
	}

	public void showListView(List<GoodsOrderProduct> goodsOrderProducts) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (GoodsOrderProduct item : goodsOrderProducts) {
			Map<String, String> dataMap = new HashMap<String, String>();
			dataMap.put("productName", item.getProductName());
			dataMap.put("billQty", item.getBillQty() + "");
			dataMap.put("readyShipQty", item.getReadyShipQty() + "");
			dataMap.put("shippedQty", item.getShippedQty() + "");
			list.add(dataMap);
			ListView listView = (ListView) findViewById(android.R.id.list);
			SimpleAdapter listAdapter = new SimpleAdapter(this, list, R.layout.product_list_view, new String[] { "productName", "billQty", "readyShipQty",
					"shippedQty" }, new int[] { R.id.productName, R.id.billQty, R.id.readyShipQty, R.id.shipQty });
			setListAdapter(listAdapter);
			setListViewHeightBasedOnChildren(listView);
		}
	}
	
	/**
	 * 取消ListView列表显示
	 */
	public void cancelShowListView(){
		List<Map<String, String>> list = new ArrayList<Map<String, String>>(0);
		SimpleAdapter listAdapter = new SimpleAdapter(this, list, R.layout.product_list_view, new String[] { "productName", "billQty", "readyShipQty",
		"shippedQty" }, new int[] { R.id.productName, R.id.billQty, R.id.readyShipQty, R.id.shipQty });
		ListView listView = (ListView) findViewById(android.R.id.list);
		setListAdapter(listAdapter);
		setListViewHeightBasedOnChildren(listView);
	}
	
	public void validate(){
		RequestParams  params = new RequestParams();
		params.put("orderNo", input_barCode.getText().toString());
		params.put("boxImeStr", input_boxNo.getText().toString());
		params.put("imeStr", input_imes.getText().toString());
		httpGet(baseUrl, params);
	}
	
}
